<!--物料多选搜索弹框-->
<template>
    <div class="archive-search-wrapper" id="archiveId" ref="archiveBoxRef">
        <div class="title" @mousedown="mousedown">
            物料档案
        </div>
        <div class="flex">
            <div class="tree-box">
                <!-- <div class="flex">
                <a-input size="small" v-model="searchName"></a-input>
                <a-button size="small" @click="treeSearch">定位</a-button>
            </div> -->
                <a-tree show-line class="tree" v-if="treeData.length > 0" :tree-data="treeData" :replaceFields="replaceFields" defaultExpandAll @select="treeSelect">
                    <a-icon slot="switcherIcon" type="down" />
                </a-tree>
            </div>

            <div class="table-box archives-popup-table">
                <a-table id="archives_tb" :columns="columns" :data-source="tableData" :customRow="customClick" bordered :pagination="false" :loading="isSearch" :row-selection="{ columnWidth: 30,selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:showDomType}" :scroll="{ x: 540, y: 330 }">
                </a-table>
            </div>
        </div>
        <div class="footer">
            <a-pagination class="pagination-box" show-size-changer :size="'small'" :page-size-options="['10','20','30','40','50']" @showSizeChange="onShowSizeChange" :page-size="pagination.pageSize" :current="pagination.current" :total="pagination.total" @change="pagination.onChange" />
            <a-button @click="submitArchives(0)">取消</a-button>
            <a-button v-show="tableData.length>0" type="primary" class="archive-save-btn" @click="submitArchives(1)">确认</a-button>
        </div>
    </div>
</template>
<script>
import { getList as listInventory } from "@/api/inventory/inventory"; //获取物料数据

import { list } from "@/api/inventory/inventoryClass"; //获取物料分类树形菜单
import { classPageListToTree, searchInTreeData } from "@/utils/tree";
import { Controlwidth } from "@/utils/antTableComponents";

const columns = [
    { title: "物料编码", dataIndex: "inventoryCode", align: 'left', width: 120 },
    { title: "物料名称", dataIndex: "inventoryName", align: 'left', width: 120 },
    { title: "规格型号", dataIndex: "inventorySpecification", align: 'left', width: 80 },
    { title: "物料属性", dataIndex: "inventoryAttribute", width: 240, ellipsis: true },
    { title: "计量方式", dataIndex: "unitType", width: 70, align: 'center', }
];
/**
 * 物料类型
 * is_purchasing:是否外购  
 * is_for_sale:是否销售 
 * is_made_self:是否自制 
 * is_semi_manufactured:是否在制 
 * is_material:是否生产耗用 
 * is_labor_cost:是否劳务费用 
 * is_suite:是否成套件  
 * is_made_request:是否委外加工
 * is_invented_key:是否虚拟键
 */
export default {
    props: {
        //物料类型
        checkType: {
            type: String,
            default: ''
        },
    },
    updated () {
        Controlwidth("archives_tb", 100)
    },
    data () {
        return {
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                size: 'small',
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.pagination.pageSize = pageSize;
                    this.getData();
                }
            },
            columns,
            tableData: [],
            customClick: (record, index) => ({
                on: {
                    dblclick: (event) => {
                        event.preventDefault();
                        console.log('物料编码点击', record, index);
                        this.$emit('check', record)
                    },
                },
            }),
            isSearch: false,

            //树形菜单
            treeData: [],
            replaceFields: {
                title: "showTitle",
            },
            selectedRowKeys: [],
            id: 'archiveId',
            inInventoryClassId: null,//物料分类id
            clickTreeCode: null,       //物料分类编码
            inputVal: null,
            showDomType: 'checkbox',

            selectData: [],//当前选中的物料
        }
    },
    created () {
        this.calssList();
        this.getData();
    },
    mounted () {
        // this.tableBody = document.getElementById('archives_tb').getElementsByClassName('ant-table-body');
        // let _this = this;
        // this.tableBody[0].onscroll = function () {
        //     // scrollTop + clientHeight == scrollHeight
        //     //  scrollTop为滚动条在Y轴上的滚动距离。
        //     // clientHeight为内容可视区域的高度。
        //     // scrollHeight为内容可视区域的高度加上溢出（滚动）的距离。
        //     if (_this.tableBody[0].scrollTop + _this.tableBody[0].clientHeight == _this.tableBody[0].scrollHeight) {
        //         console.log('我到底部了')
        //         _this.pagination.current++;
        //         _this.getData();
        //     }
        // }
    },
    methods: {
        onShowSizeChange (current, pageSize) {
            this.pagination.pageSize = pageSize;
            this.pagination.current = current;
            console.log(current, pageSize);
            this.getData();
        },
        getData (page) {
            if (page) {
                this.pagination.current = 1;
            }
            //获取右侧表数据
            var _this = this;
            let params = {
                current: this.pagination.current,
                size: this.pagination.pageSize,
                key: this.inputVal,
                // inInventoryClassId: this.inInventoryClassId,
                inInventoryClassCode: this.clickTreeCode,
                propertyStr: this.checkType,//物料类型
            };
            if (!this.isSearch) {
                this.isSearch = true;
                listInventory(params).then((res) => {
                    if (res.code == 200) {

                        this.tableData = res.data.records;

                        this.tableData.forEach(item => {
                            item.key = item.id;
                            let attribute = [];
                            if (item.isPurchasing) {
                                attribute.push('外购');
                            }
                            if (item.isForSale) {
                                attribute.push('销售');
                            }
                            if (item.isMadeSelf) {
                                attribute.push('自制');
                            }
                            if (item.isMaterial) {
                                attribute.push('生产耗用');
                            }
                            if (item.isLaborCost) {
                                attribute.push('劳务费用');
                            }
                            if (item.isSuite) {
                                attribute.push('成套件');
                            }
                            if (item.isMadeRequest) {
                                attribute.push('委外');
                            }
                            if (item.isInventedKey) {
                                attribute.push('虚拟件');
                            }
                            item.inventoryAttribute = attribute.join('，')
                        });
                        this.pagination.total = res.data.total;
                    } else {
                        // _this.$message.warning(res.message);
                    }
                    this.isSearch = false;
                });
            }

        },
        handleEnter () {
            if (this.tableData != '' && this.tableData != null) {
                this.$emit('check', this.tableData[0])
            } else {
                this.$message.warning('请选择一条数据')
                return;
            }
        },
        changePosition (position) {
            console.log("当前坐标：", position)
            let offsetWidth = document.body.offsetWidth;  //(包括边线的宽)
            let offsetHeight = document.body.offsetHeight;   //(包括边线的宽)

            let leftOff = position.left + 350;
            let topOff = position.top + 256;

            let boxWidth = this.$refs.archiveBoxRef.style.width;
            let boxHeight = this.$refs.archiveBoxRef.style.height;
            console.log(offsetWidth, offsetHeight, leftOff, topOff, boxWidth, boxHeight)
            if ((leftOff + boxWidth / 2) > offsetWidth) {
                leftOff = position.left - 350 - 50;
            }
            // if((topOff + boxHeight / 2) > offsetHeight){
            //       topOff = position.top - 260 ;
            // }

            this.$nextTick(() => {
                //   this.$refs.archiveBoxRef.style.top = (topOff) + 'px';
                //   this.$refs.archiveBoxRef.style.left = (leftOff) + 'px';
            })
        },
        treeSelect (key, rows) {
            //左侧树形菜单
            this.pagination.current = 1;
            this.inInventoryClassId = rows.node.dataRef.id;
            this.clickTreeCode = rows.node.dataRef.classCode;
            this.getData();
        },
        calssList () {
            //获取树形菜单数据
            list().then((res) => {
                if (res.code == 200) {
                    console.log(res.data);
                    const childrenNav = [];
                    classPageListToTree(res.data, childrenNav, 0);
                    console.log("childrenNav", childrenNav);
                    let childrenData = this.getTreeData(childrenNav);
                    this.treeData = [
                        {
                            title: "物料分类",
                            showTitle: "物料分类",
                            key: "-1",
                            children: childrenData,
                        },
                    ];
                }
            });
        },
        getTreeData (data) {
            //递归添加显示的tree showTitle
            for (let i = 0; i < data.length; i++) {
                let element = data[i];
                this.$set(element, "showTitle", `(${element.classCode}) ${element.title}`);
                if (element.children) {
                    this.getTreeData(element.children);
                }
            }
            return data;
        },
        onSelectChange (selectedRowKeys, data) {
            console.log('selectedRowKeys changed: ', selectedRowKeys, data);
            this.selectedRowKeys = selectedRowKeys;


            this.selectData = _.uniqBy(this.selectData.concat(data), 'id');//数组合并后 id相同去重
            let selectEndData = [];
            this.selectedRowKeys.forEach(el => {
                this.selectData.forEach((item, index) => {
                    if (el == item.key) {
                        selectEndData.push(item);
                    }
                })
            });
            console.log(selectEndData);
            this.selectedRowData = selectEndData;
        },
        submitArchives (t) {
            if (t == 0) {
                this.$emit('check', 0)
            } else {
                if (this.selectedRowKeys.length <= 0) {
                    this.$message.warning('请至少勾选一条数据');
                } else {
                    this.$emit('check', this.selectedRowData)
                }
            }
        },
        mousedown (event) {
            console.log(event, this.id);
            this.selectElement = document.getElementById(this.id);
            var div1 = this.selectElement;
            //   this.selectElement.style.cursor = "move";
            var distanceX = event.clientX - this.selectElement.offsetLeft;
            var distanceY = event.clientY - this.selectElement.offsetTop;
            document.onmousemove = function (ev) {
                var oevent = ev || event;
                div1.style.left = oevent.clientX - distanceX + 350 + "px";
                div1.style.top = oevent.clientY - distanceY + 225 + "px";
            };
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                div1.style.cursor = "default";
            };
        },
    }
}
</script>
<style lang="less" scoped>
    .archive-search-wrapper {
        position: fixed;
        top: 50%;
        margin-top: -225px;
        left: 50%;
        margin-left: -350px;
        z-index: 100;
        // border: 2px solid #a7abb0;
        box-shadow: 0px 0px 10px #888;
        background: #fff;
        .title {
            padding-left: 20px;
            text-align: left;
            height: 40px;
            line-height: 40px;
            font-size: 16px;
            border-bottom: 1px solid #a7abb0;
            cursor: move;
        }
        .flex {
            display: flex;
            height: 380px;
        }
        .ant-table-wrapper {
            padding: 0px;
        }
        .ant-table-tbody {
            cursor: pointer;
        }

        .tree-box {
            width: 200px;
            background: #fff;
            overflow-y: auto;
            text-align: left;
            padding-left: 10px;
            padding-top: 10px;
        }
        .table-box {
            width: 700px;
            border-left: 1px solid #a7abb0;
            margin-left: -2px;
            padding: 10px;
        }
        .archive-save-btn {
            margin-left: 5px;
        }
        .pagination-box {
            float: left;
            line-height: 40px;
            padding-left: 200px;
        }
        .footer {
            height: 40px;
            line-height: 40px;
            border-top: 1px solid #a7abb0;
            text-align: right;
            padding-right: 20px;
        }
        .ant-table-thead > tr:first-child > th:first-child {
            border-top-left-radius: 0;
        }
        .ant-table-thead > tr:first-child > th:last-child {
            border-top-right-radius: 0;
        }
    }
    #archives_tb {
        .ant-table-tbody > tr > td {
            padding: 0px 2px !important;
        }
    }
</style>
<style lang="less" scoped>
    /deep/.ant-tree-title {
        max-width: none !important;
    }
    /deep/.footer .ant-select-selection {
        border: 1px solid #ccc !important;
    }
</style>